package com.alexmullans.mytvcompanion;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class TVDBAdapter {

	public int serverTime;
	private final String apiKey = "49FF3082EF06CF50";
	private DocumentBuilder db;

	/**
	 * @param args
	 * @throws IOException
	 */
	public TVDBAdapter() {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document dom;
		try {
			db = dbf.newDocumentBuilder();
			dom = queryApi("http://www.thetvdb.com/api/Updates.php?type=none");
			getServerTime(dom);
		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
		}
	}

	private void getServerTime(Document dom) {
		NodeList nl = dom.getDocumentElement().getElementsByTagName("Time");
		if (nl != null && nl.getLength() > 0) {
			for (int i = 0; i < nl.getLength(); i++) {
				Element el = (Element) nl.item(i);
				serverTime = Integer
						.parseInt(el.getFirstChild().getNodeValue());
			}
		}
	}

	public HashMap<Integer, String> getMatchingShows(String query) {
		HashMap<Integer, String> toReturn = new HashMap<Integer, String>();
		Document dom = queryApi("http://www.thetvdb.com/api/GetSeries.php?seriesname="
				+ query);
		NodeList nl = dom.getDocumentElement().getElementsByTagName("Series");
		if (nl != null && nl.getLength() > 0) {
			for (int i = 0; i < nl.getLength(); i++) {
				Element el = (Element) nl.item(i);
				String seriesId = el.getElementsByTagName("seriesid").item(0)
						.getNodeValue();
				String seriesName = el.getElementsByTagName("SeriesName")
						.item(0).getNodeValue();
				toReturn.put(Integer.parseInt(seriesId), seriesName);
			}
		}
		return toReturn;
	}

	private Document queryApi(String apiUrl) {
		try {
			return db.parse(new InputSource(new URL(apiUrl).openStream()));
		} catch (SAXException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
